
export const VxeModalMixin = {
  props: {
    formData: {
      type: Object,
      required: false,
      default: () => {}
    },
    value: {
      required: true,
      type: Boolean
    }
  },
  data() {
    return {
      loading: false,
      modelValue: {},
      api: null,
      rules: {}
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    isMobile() {
      return this.$store.state.app.device === 'mobile'
    }
  },
  created() {
    this.setRuleMsg()
    this.initData(this.modelValue, this.formData)
  },
  methods: {
    initData(modelValue, formData = {}) {
      for (const m in modelValue) {
        if (formData[m] === undefined || formData[m] === null) {
          continue
        }
        const mTypeObj = Object.prototype.toString.call(modelValue[m])
        // const mType = mTypeObj.substring(7, mTypeObj.length - 1).toString()
        if (mTypeObj === '[object Undefined]' || mTypeObj === '[object Null]') {
          modelValue[m] = formData[m]
        } else if (mTypeObj === '[object String]') {
          modelValue[m] = modelValue[m] || formData[m]
        } else if (mTypeObj === '[object Array]') {
          modelValue[m] = (modelValue[m].length === 0) ? formData[m] : modelValue[m]
        } else if (mTypeObj === '[object Number]') {
          modelValue[m] = modelValue[m] || formData[m]
        } else if (mTypeObj === '[object Object]') {
          this.initData(modelValue[m], formData[m])
        }
      }
    },
    setRuleMsg() {
      for (const obj in this.rules) {
        this.rules[obj].forEach(element => {
          if (element['required'] && !element['message']) {
            element['message'] = '不能为空'
          }
        })
      }
    },
    async clickSubmitBtn() {
      if (!this.api) {
        this.$message({ type: 'error', message: '请配置保存方法' })
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.api(this.modelValue).then(({ code, msg }) => {
            if (code === 200200) {
              this.dialogVisible = false
              this.$emit('success', this.modelValue)
              this.loading = false
            }
            this.$message({ type: code === 200200 ? 'success' : 'error', message: msg || '保存成功' })
          }).finally(() => {
            if (this.loading) {
              setTimeout(() => {
                this.loading = false
              }, 1500)
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
